/*
 * @lc app=leetcode.cn id=67 lang=csharp
 *
 * [67] 二进制求和
 */

// @lc code=start
public class Solution {
    public string AddBinary(string a, string b) {
        int aLen = a.Length;
        int bLen = b.Length;
        
        byte carry = (byte)0;
        byte abit = (byte)0;
        byte bbit = (byte)0;
        byte bit = (byte)0;
        var newCarry = (byte)0;
        StringBuilder sb = new StringBuilder();
        for(int i = 0; i < Math.Max(aLen, bLen); i++)
        {
            abit = i < aLen ? (byte)(a[aLen - 1 - i] - '0') : (byte)0;
            bbit = i < bLen ? (byte)(b[bLen - 1 - i] - '0') : (byte)0;
            bit = (byte)(abit ^ bbit ^ carry);
            newCarry = (byte)((abit & bbit) | (abit & carry) | (bbit & carry));
            sb.Insert(0, bit);
            carry = (byte)newCarry;
        }
        if(carry == 1)
        {
            sb.Insert(0, carry);
        }
        return sb.ToString();
    }
}
// @lc code=end

